<template>
    <n-form
        style="margin-top: 24px"
        ref="formRef"
        :model="form"
        :rules="rules"
        label-placement="left"
        label-width="120"
        require-mark-placement="right-hanging"
    >


        <n-form-item label="资源类型" path="type">
            <n-select v-model:value="form.type" placeholder="请选择资源类型" :options="modelOptions" label-field="name"
                      value-field="sn" @update:value="handleTypeChange">
            </n-select>
        </n-form-item>
        <n-form-item label="资源名称" path="name">
            <n-input v-model:value="form.name" placeholder="请输入资源名称"></n-input>
        </n-form-item>

        <template v-for="item in items" :key="item.field">
            <n-form-item
                :label="item.field=='defaultModel'?'大模型型号':item.field"
                :path="item.field"
                :required="item.required"
            >
                <div class="flex-col w-full">
                    <n-input
                        v-model:value="form[item.field]"
                        :placeholder="`请输入${item.field=='defaultModel'?'要使用的大模型型号':item.field}${item.required?'':'，此项可以留空，系统会自动应用默认值'}`"
                    />
                    <span v-if="item.remark" class="text_tip">{{ item.remark }}</span>
                </div>
            </n-form-item>
        </template>
        <n-form-item label="请求频率限制">
            <n-space vertical>
                <n-input-group>
                    <n-input-number
                        v-model:value="rateLimitForm.minute"
                        :min="0"

                        placeholder="默认不限制"
                        style="width: 150px"
                        @update:value="handleRateLimitChange('minute')"
                    />
                    <n-input-group-label>/ 每分钟</n-input-group-label>
                </n-input-group>
                <n-input-group>
                    <n-input-number
                        v-model:value="rateLimitForm.hour"
                        :min="0"
                        placeholder="默认不限制"
                        style="width: 150px"
                        @update:value="handleRateLimitChange('hour')"
                    />
                    <n-input-group-label>/ 每小时</n-input-group-label>
                </n-input-group>
                <n-input-group>
                    <n-input-number
                        v-model:value="rateLimitForm.day"
                        :min="0"
                        placeholder="默认不限制"
                        style="width: 150px"
                        @update:value="handleRateLimitChange('day')"
                    />
                    <n-input-group-label>/ 每天</n-input-group-label>
                </n-input-group>
            </n-space>
        </n-form-item>
    </n-form>
</template>

<script setup>
import {onMounted, reactive, ref, watch} from 'vue'
import {JBoltApi} from '@/service/request'

const props = defineProps({
    id: {
        type: String
    }
})


const formRef = ref(null)
const items = ref(null)

const form = ref({
    id: '',
    name: '',
    type: null,
    defaultModel: '',
    apiKey: '',
    apiSecret: '',
    apiUrl: '',
    limits: '',
    createTime: '',
})

const rateLimitForm = reactive({
    minute: null,
    hour: null,
    day: null
})

const rules =reactive(
    {
        type: {
            required: true,
            message: '请选择资源类型',
            trigger: 'change'
        },
        name: {
            required: true,
            message: '请输入资源名称',
			pattern: /\S/, // 至少有一个非空白字符
            trigger: 'change'
        }
    }
)

// 动态添加验证规则
watch(() => items.value, (newItems) => {
    if (newItems) {
        newItems.forEach(item => {
            if (item.required) {
                rules[item.field] = {
                    required: true,
					pattern: /\S/, // 至少有一个非空白字符
                    message: `请输入${item.field}`,
                    trigger: 'blur'
                }
            }else {
                delete rules[item.field]
            }
        })
    }
    console.log('Updated rules:', rules);
}, {immediate: true, deep: true})

// 处理频率限制变化
function handleRateLimitChange(unit) {
    const limits = []
    if (rateLimitForm.minute > 0) {
        limits.push({unit: 'minute', times: rateLimitForm.minute})
    }
    if (rateLimitForm.hour > 0) {
        limits.push({unit: 'hour', times: rateLimitForm.hour})
    }
    if (rateLimitForm.day > 0) {
        limits.push({unit: 'day', times: rateLimitForm.day})
    }
    form.value.limits = JSON.stringify(limits)
}

// 加载编辑数据时解析频率限制
function parseLimits(limitsStr) {
    if (!limitsStr) return
    try {
        const limits = JSON.parse(limitsStr)
        limits.forEach(limit => {
            rateLimitForm[limit.unit] = limit.times
        })
    } catch (error) {
        console.error('解析频率限制失败:', error)
    }
}

// 加载编辑数据
async function loadEditData() {
    if (props.id) {
        const {result} = await JBoltApi.get(`/aiResource/getById/${props.id}`)

        form.value = result.data

        if (form.value.type) {
            const selectedModel = modelOptions.value.find(item => item.sn === form.value.type)
            if (selectedModel) {
                items.value = selectedModel.configItem
            }
        }

        // 解析频率限制
        parseLimits(result.data.limits)
    }
}

defineExpose({
    submit
})

async function submit(fun) {
    await formRef.value?.validate()

    console.debug('提交表单', form.value)

    let url = props.id ? '/aiResource/update' : '/aiResource/add'

    await JBoltApi.tryPost(url, form.value)


    if (fun) {
        fun()
    }

    return true
}

const modelOptions = ref([])

function handleTypeChange(value) {
    const selectedModel = modelOptions.value.find(item => item.sn === value)
    if (selectedModel) {
        items.value = []
        items.value = selectedModel.configItem
    }
}

function loadModelTypeList() {
    JBoltApi.tryGet('/aiModelType/list').then(res => {
        modelOptions.value = res.data

        if (props.id) {
            loadEditData()
        }
    }).catch((error) => {
        console.error(error)
    })
}

onMounted(() => {
    loadModelTypeList()


})

</script>

<style scoped lang="scss">
.text_tip {
    font-size: 12px;
    color: #999;
}
</style>